<template>
  <view class="page-container">
    <uni-card 
      title="水滴张力计算" 
      :is-full="true"
      :is-shadow="false"
      class="full-card"
    >
      <uni-forms ref="formRef" :model="formData" label-width="140px">
        <!-- 页面顶部导航和标题 -->
        <view class="page-header">
          <text class="page-subtitle">精确测量液滴特性的专业工具</text>
        </view>
        
        <!-- 基本参数 -->
        <uni-section title="基本参数" type="line" class="section-card">
          <view class="section-content"> 
            <uni-forms-item label="液滴密度" required>
              <view class="input-group">
                <uni-easyinput v-model="formData.drop_density" type="number" class="primary-input" />
                <text class="unit">kg/m³</text>
              </view>
              <text class="description">液滴的密度，影响计算结果的准确性</text>
            </uni-forms-item>
            
            <uni-forms-item label="连续相密度" required>
              <view class="input-group">
                <uni-easyinput v-model="formData.continuous_density" type="number" class="primary-input" />
                <text class="unit">kg/m³</text>
              </view>
              <text class="description">连续相的密度，用于计算界面张力</text>
            </uni-forms-item>
            
            <uni-forms-item label="针头直径" required>
              <view class="input-group">
                <uni-easyinput v-model="formData.needle_diameter_mm" type="number" class="primary-input" />
                <text class="unit">mm</text>
              </view>
              <text class="description">针头的实际直径，用于校准尺寸</text>
            </uni-forms-item>
          </view>
        </uni-section>
        
        <!-- 图片上传区域 -->
        <view class="image-section section-card">
          <uni-section title="图像分析" type="line">
            <view class="section-content">
              <view class="preview-container">
                <image 
                  v-if="imagePreview" 
                  :src="imagePreview" 
                  mode="aspectFit" 
                  class="preview-image"
                ></image>
                <view v-else class="empty-preview">
                  <uni-icons type="image" size="50" color="#ddd"></uni-icons>
                  <text class="empty-text">暂无图片</text>
                </view>
              </view>
              <view class="image-actions">
                <button class="action-button select-button" @click="chooseImage">
                  <text class="button-text">选择图片</text>
                </button>
                <button class="action-button region-button" @click="goToRegionSelector" :disabled="!imagePreview">
                  <text class="button-text">选择区域</text>
                </button>
              </view>
            </view>
          </uni-section>
        </view>
        
        <!-- 区域状态 -->
        <uni-section title="区域状态" type="line" v-if="imagePreview">
          <view class="section-content">
            <view class="region-status">
              <view class="region-item" :class="{'region-selected': isValidRegion(formData.drop_region)}">
                <view class="region-icon drop-icon"></view>
                <view class="region-info">
                  <text class="region-name">水滴区域</text>
                  <text class="region-detail" v-if="isValidRegion(formData.drop_region)">
                    已选择 {{ Math.abs(formData.drop_region[1][0] - formData.drop_region[0][0]) }}×{{ Math.abs(formData.drop_region[1][1] - formData.drop_region[0][1]) }}px
                  </text>
                  <text class="region-detail" v-else>未选择</text>
                </view>
              </view>
              
              <view class="region-item" :class="{'region-selected': isValidRegion(formData.needle_region)}">
                <view class="region-icon needle-icon"></view>
                <view class="region-info">
                  <text class="region-name">针头区域</text>
                  <text class="region-detail" v-if="isValidRegion(formData.needle_region)">
                    已选择 {{ Math.abs(formData.needle_region[1][0] - formData.needle_region[0][0]) }}×{{ Math.abs(formData.needle_region[1][1] - formData.needle_region[0][1]) }}px
                  </text>
                  <text class="region-detail" v-else>未选择</text>
                </view>
              </view>
            </view>
          </view>
        </uni-section>
        
        <!-- 高级选项 -->
        <uni-section title="高级设置" type="line" class="section-card">
          <view class="section-content">
            <uni-collapse class="custom-collapse">
              <uni-collapse-item title="处理选项" class="collapse-item">
                <view class="advanced-options">
                  <uni-forms-item label="等待时间">
                    <view class="input-group">
                      <uni-number-box v-model="formData.wait_time" :min="1" :max="60" class="custom-number-box" />
                      <text class="unit">秒</text>
                    </view>
                    <text class="description">图像处理的等待时间</text>
                  </uni-forms-item>
                  
                  <uni-forms-item label="保存图片">
                    <view class="switch-group">
                      <uni-switch 
                        :checked="formData.save_images_boole"
                        @change="(e) => formData.save_images_boole = e.value" 
                        class="custom-switch"
                      />
                      <text class="description">是否保存处理后的图片</text>
                    </view>
                  </uni-forms-item>
                  
                  <uni-forms-item label="创建文件夹">
                    <view class="switch-group">
                      <uni-switch 
                        :checked="formData.create_folder_boole"
                        @change="(e) => formData.create_folder_boole = e.value" 
                        class="custom-switch"
                      />
                      <text class="description">是否创建新的输出文件夹</text>
                    </view>
                  </uni-forms-item>
                </view>
              </uni-collapse-item>
              
              <uni-collapse-item title="显示选项" class="collapse-item">
                <view class="advanced-options">
                  <uni-forms-item label="显示张力图">
                    <view class="switch-group">
                      <uni-switch 
                        :checked="formData.interfacial_tension_boole"
                        @change="(e) => formData.interfacial_tension_boole = e.value" 
                        class="custom-switch"
                      />
                      <text class="description">显示界面张力变化图</text>
                    </view>
                  </uni-forms-item>
                  
                  <uni-forms-item label="显示轮廓图">
                    <view class="switch-group">
                      <uni-switch 
                        :checked="formData.profiles_boole"
                        @change="(e) => formData.profiles_boole = e.value" 
                        class="custom-switch"
                      />
                      <text class="description">显示液滴轮廓拟合图</text>
                    </view>
                  </uni-forms-item>
                  
                  <uni-forms-item label="显示残差图">
                    <view class="switch-group">
                      <uni-switch 
                        :checked="formData.residuals_boole"
                        @change="(e) => formData.residuals_boole = e.value" 
                        class="custom-switch"
                      />
                      <text class="description">显示拟合残差分布图</text>
                    </view>
                  </uni-forms-item>
                </view>
              </uni-collapse-item>
            </uni-collapse>
          </view>
        </uni-section>
        
        <!-- 服务器配置部分 -->
        <!-- <view class="server-config section-card">
          <uni-section title="服务器配置" type="line">
            <view class="section-content">
              <view class="server-input-group">
                <text class="server-label">服务器地址:</text>
                <uni-easyinput v-model="serverConfig.host" placeholder="输入服务器IP地址" class="server-input" />
              </view>
              <view class="server-input-group">
                <text class="server-label">端口:</text>
                <uni-easyinput v-model="serverConfig.port" type="number" placeholder="输入端口号" class="server-input" />
              </view>
              <view class="server-input-group">
                <text class="server-label">路径前缀:</text>
                <uni-easyinput v-model="serverConfig.prefix" placeholder="例如: /OpenDrop" class="server-input" />
              </view>
              <button @click="saveServerConfig" class="server-save-btn">保存配置</button>
            </view>
          </uni-section> -->
        <!-- </view> -->
        
        <view class="action-container">
          <button type="primary" 
            @click="submitForm" 
            :loading="loading" 
            :disabled="!imagePreview || loading"
            class="action-button calculate-button"
          >
            <uni-icons v-if="!loading" type="refresh" size="16" color="#fff"></uni-icons>
            {{ loading ? '计算中...' : '开始计算' }}
          </button>
          
          <button type="primary"
            @click="saveResult"
            :disabled="!calculationResult"
            class="action-button save-button"
          >
            <uni-icons type="save" size="16" color="#fff"></uni-icons>
            保存结果
          </button>
        </view>
      </uni-forms>
      
      <!-- 结果展示区域 -->
      <view class="result-section section-card" v-if="calculationResult">
        <uni-section title="计算结果" type="line">
          <view class="section-content result-content">
            <!-- 结构化数据显示 -->
            <view class="json-data">
              <view class="data-group">
                <view class="group-title">基本参数</view>
                <view class="data-item">
                  <text class="data-label">界面张力 (IFT):</text>
                  <text class="data-value">{{ calculationResult[0]['IFT (mN/m)']?.toFixed(5) }} mN/m</text>
                </view>
                <view class="data-item">
                  <text class="data-label">体积:</text>
                  <text class="data-value">{{ calculationResult[0]['Volume (uL)']?.toFixed(5) }} μL</text>
                </view>
                <view class="data-item">
                  <text class="data-label">表面积:</text>
                  <text class="data-value">{{ calculationResult[0]['Area (mm2)']?.toFixed(5) }} mm²</text>
                </view>
              </view>
              
              <view class="data-group">
                <view class="group-title">几何参数</view>
                <view class="data-item">
                  <text class="data-label">顶点半径:</text>
                  <text class="data-value">{{ calculationResult[0]['Apex radius (px)']?.toFixed(5) }} px</text>
                </view>
                <view class="data-item">
                  <text class="data-label">旋转角度:</text>
                  <text class="data-value">{{ calculationResult[0]['Rotation (degree)']?.toFixed(5) }}°</text>
                </view>
                <view class="data-item">
                  <text class="data-label">顶点坐标:</text>
                  <view class="coord-value">
                    <text>x: {{ calculationResult[0]['x-apex (px)']?.toFixed(5) }} px</text>
                    <text>y: {{ calculationResult[0]['y-apex (px)']?.toFixed(5) }} px</text>
                  </view>
                </view>
              </view>
              
              <view class="data-group">
                <view class="group-title">无量纲参数</view>
                <view class="data-item">
                  <text class="data-label">Bond数:</text>
                  <text class="data-value">{{ calculationResult[0]['Bond number']?.toFixed(5) }}</text>
                </view>
                <view class="data-item">
                  <text class="data-label">Worthington数:</text>
                  <text class="data-value">{{ calculationResult[0]['Worthington number']?.toFixed(5) }}</text>
                </view>
              </view>
            </view>
          </view>
        </uni-section>
      </view>
    </uni-card>
  </view>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import RegionSelector from '@/components/RegionSelector.vue';
import CanvasRegionSelector from '@/components/CanvasRegionSelector.vue';

// 服务器配置（固定值）  http://s.wangchenyang.info/openDrop
const apiBaseUrl = "http://47.97.2.25:7010";

// 表单引用
const formRef = ref(null);

// 状态管理
const loading = ref(false);
const imagePreview = ref('');
const calculationResult = ref(null);
const currentProjectId = ref('');

// 表单数据
const formData = reactive({
  drop_density: 1053.0,
  continuous_density: 1016.6,
  needle_diameter_mm: 0.71,
  directory_string: './output',
  filename: '1.png',
  image_source: 'Local images',
  import_files: [],
  save_images_boole: false,
  number_of_frames: 1,
  wait_time: 5,
  create_folder_boole: false,
  interfacial_tension_boole: false,
  profiles_boole: false,
  residuals_boole: false,
  screen_resolution: [1440, 900],
  time_string: null,
  drop_region: [[197, 143], [372, 337]],
  needle_region: [[207, 79], [351, 147]]
});

// 区域限制
const regionLimits = reactive({
  minX: 0,
  maxX: 1000,
  minY: 0,
  maxY: 1000
});

// 判断区域是否有效
const isValidRegion = (region) => {
  if (!region || !region[0] || !region[1]) return false;
  
  const width = Math.abs(region[1][0] - region[0][0]);
  const height = Math.abs(region[1][1] - region[0][1]);
  
  // 区域至少要有一定大小才算有效
  return width > 10 && height > 10;
};

// 页面加载时检查是否有传入的图片
onMounted(async () => {
  // 检查是否有传入的图片路径（来自project页面）
  const analyzedImagePath = uni.getStorageSync('analyzedImagePath');
  if (analyzedImagePath) {
    try {
      console.log('接收到项目页面传入的图片路径:', analyzedImagePath);
      imagePreview.value = analyzedImagePath;
      
      // 使用Promise包装图片加载过程
      await new Promise(async (resolve) => {
        // 获取图片信息
        const imageInfo = await uni.getImageInfo({
          src: analyzedImagePath
        });
        
        console.log('图片信息:', imageInfo);
        
        // 更新区域限制
        regionLimits.minX = 0;
        regionLimits.maxX = imageInfo.width;
        regionLimits.minY = 0;
        regionLimits.maxY = imageInfo.height;
        
        // 设置默认区域初始值 - 自动设置水滴和针头区域的初始位置
        const defaultDropRegion = [
          [Math.floor(imageInfo.width * 0.3), Math.floor(imageInfo.height * 0.3)],
          [Math.floor(imageInfo.width * 0.7), Math.floor(imageInfo.height * 0.7)]
        ];
        
        const defaultNeedleRegion = [
          [Math.floor(imageInfo.width * 0.3), Math.floor(imageInfo.height * 0.1)],
          [Math.floor(imageInfo.width * 0.7), Math.floor(imageInfo.height * 0.3)]
        ];
        
        // 将默认区域保存到缓存，作为区域选择页面的初始值
        uni.setStorageSync('defaultDropRegion', defaultDropRegion);
        uni.setStorageSync('defaultNeedleRegion', defaultNeedleRegion);
        
        // 文件名处理
        formData.filename = analyzedImagePath.split('/').pop();
        
        // 转换图片为base64，提前准备好计算数据
        try {
          const base64Data = await pathToBase64(analyzedImagePath);
          formData.import_files = [base64Data]; // 提前转换并保存
        } catch (e) {
          console.error('图片转换失败:', e);
        }
        
        resolve();
      });
      
      // 延迟后再引导用户进入区域选择，避免闪烁
      setTimeout(() => {
        uni.showToast({
          title: '请选择水滴和针头区域',
          icon: 'none',
          duration: 2000
        });
        
        setTimeout(() => {
          goToRegionSelector();
        }, 1000);
      }, 1000); // 增加延迟时间
      
    } catch (e) {
      console.error('处理传入图片失败:', e);
      uni.showToast({
        title: '处理图片失败',
        icon: 'none'
      });
      // 清除存储，避免影响下次使用
      uni.removeStorageSync('analyzedImagePath');
    }
  }
  
  // 获取当前项目ID
  const projectId = uni.getStorageSync('currentProjectId');
  if (projectId) {
    currentProjectId.value = projectId;
    console.log('接收到项目ID:', projectId);
  }
  
  // 监听区域选择事件
  uni.$on('regionsSelected', handleRegionsSelected);
  
  return () => {
    // 组件卸载时移除事件监听
    uni.$off('regionsSelected', handleRegionsSelected);
  };
});

// 处理区域选择结果
const handleRegionsSelected = async (data) => {
  console.log('收到选择的区域:', data);
  
  if (data && data.dropRegion && data.needleRegion) {
    // 更新表单数据中的区域
    formData.drop_region = data.dropRegion;
    formData.needle_region = data.needleRegion;
    
    // 从缓存中移除选择的区域
    uni.removeStorageSync('selectedDropRegion');
    uni.removeStorageSync('selectedNeedleRegion');
    
    // 如果已经提前转换了图片，则直接使用
    if (formData.import_files.length === 0 && imagePreview.value) {
      try {
        // 转换并保存图片
        const base64Data = await pathToBase64(imagePreview.value);
        formData.import_files = [base64Data];
      } catch (e) {
        console.error('图片转换失败:', e);
        uni.showToast({
          title: '图片处理失败',
          icon: 'none'
        });
      }
    }
    
    // 提示用户区域已设置
    uni.showToast({
      title: '区域设置成功',
      icon: 'success'
    });
    
    // 现在可以安全地清除图片路径，因为已经转换为base64并存储在formData中
    // uni.removeStorageSync('analyzedImagePath'); // 不要立即删除，保留图片以便重新选择区域
    
    // 显示区域选择结果，使用延时避免UI闪烁
    setTimeout(() => {
      uni.showModal({
        title: '区域选择完成',
        content: '水滴和针头区域已设置，您可以点击"开始计算"按钮进行计算',
        showCancel: false,
        confirmText: '确定'
      });
    }, 300);
  }
};

// 封装请求方法
const apiRequest = async (endpoint, data) => {
  try {
    const url = `${apiBaseUrl}${endpoint}`;
    console.log('请求URL:', url);
    
    const res = await uni.request({
      url: url,
      method: 'POST',
      header: {
        'content-type': 'application/json'
      },
      data: data,
      timeout: 30000
    });
    
    console.log('响应状态:', res);
    
    if (res.statusCode === 200) {
      return res.data;
    } else {
      throw new Error(res.data?.message || `HTTP错误: ${res.statusCode}`);
    }
  } catch (e) {
    console.error(`API请求失败 (${endpoint}):`, e);
    
    if (e.errMsg && e.errMsg.includes('fail')) {
      if (e.errMsg.includes('timeout')) {
        throw new Error('请求超时，请检查服务器是否正常运行');
      } else if (e.errMsg.includes('refused')) {
        throw new Error('连接被拒绝，请检查网络连接');
      } else {
        throw new Error(`网络错误: ${e.errMsg}`);
      }
    }
    
    throw e;
  }
};

// 工具方法
const pathToBase64 = async (path) => {
  return new Promise((resolve, reject) => {
    uni.getFileSystemManager().readFile({
      filePath: path,
      encoding: 'base64',
      success: res => {
        let base64Str = res.data;
        while (base64Str.length % 4) {
          base64Str += '=';
        }
        resolve(base64Str);
      },
      fail: err => reject(err)
    });
  });
};

// 选择图片
const chooseImage = async () => {
  try {
    const res = await uni.chooseImage({
      count: 1,
      sizeType: ['original'],
      sourceType: ['album', 'camera'],
      extension: ['png', 'jpg', 'jpeg']
    });
    
    imagePreview.value = res.tempFilePaths[0];
    
    // 获取图片信息
    const imageInfo = await uni.getImageInfo({
      src: imagePreview.value
    });
    console.log('图片信息:', imageInfo);
    
    // 更新区域限制
    regionLimits.minX = 0;
    regionLimits.maxX = imageInfo.width;
    regionLimits.minY = 0;
    regionLimits.maxY = imageInfo.height;
    
    // 验证和调整区域
    const validateAndAdjustRegion = (region) => {
      return [
        [
          Math.min(Math.max(region[0][0], 0), imageInfo.width),
          Math.min(Math.max(region[0][1], 0), imageInfo.height)
        ],
        [
          Math.min(Math.max(region[1][0], 0), imageInfo.width),
          Math.min(Math.max(region[1][1], 0), imageInfo.height)
        ]
      ];
    };
    
    // 调整区域
    formData.drop_region = validateAndAdjustRegion(formData.drop_region);
    formData.needle_region = validateAndAdjustRegion(formData.needle_region);
    
    console.log('区域设置:', {
      dropRegion: formData.drop_region,
      needleRegion: formData.needle_region
    });
    
    // 转换并保存图片
    const base64Data = await pathToBase64(imagePreview.value);
    formData.filename = res.tempFilePaths[0].split('/').pop();
    formData.import_files = [base64Data];
    
    // 重置计算结果
    calculationResult.value = null;
  } catch (e) {
    console.error('选择图片失败:', e);
    uni.showToast({
      title: '选择图片失败',
      icon: 'none'
    });
  }
};

// 验证区域
const validateRegions = () => {
  const isValidRegion = (region) => {
    return region && 
           region.length === 2 && 
           region[0].length === 2 && 
           region[1].length === 2 &&
           region[0][0] < region[1][0] && 
           region[0][1] < region[1][1];
  };
  
  if (!isValidRegion(formData.drop_region)) {
    throw new Error('无效的水滴区域坐标');
  }
  
  if (!isValidRegion(formData.needle_region)) {
    throw new Error('无效的针头区域坐标');
  }
};

// 提交表单
const submitForm = async () => {
  if (!formData.import_files.length) {
    uni.showToast({
      title: '请先选择图片',
      icon: 'none'
    });
    return;
  }
  
  if (!isValidRegion(formData.drop_region) || !isValidRegion(formData.needle_region)) {
    uni.showToast({
      title: '请先完成区域选择',
      icon: 'none'
    });
    
    // 引导用户去选择区域
    setTimeout(() => {
      goToRegionSelector();
    }, 1500);
    
    return;
  }
  
  try {
    // 验证区域坐标
    validateRegions();
    
    loading.value = true;
    
    // 使用封装的请求方法
    const result = await apiRequest('/openDrop', {
      ...formData,
      image_source: 'base64',
      time_string: new Date().toISOString()
    });
    
    if (result) {
      // 取data数组的第一个元素作为计算结果
      calculationResult.value = result;
      console.log('计算结果:', result);
      uni.showToast({
        title: '计算成功',
        icon: 'success'
      });
    } else {
      throw new Error('服务器返回数据格式错误');
    }
  } catch (e) {
    console.error('计算失败:', e);
    uni.showToast({
      title: e.message || '计算失败',
      icon: 'none'
    });
  } finally {
    loading.value = false;
  }
};

// 计算是否有负值
const hasNegativeValues = computed(() => {
  return calculationResult.value && (
    calculationResult.value.IFT < 0 ||
    calculationResult.value.Volume < 0 ||
    calculationResult.value.Area < 0
  );
});

// 保存结果
const saveResult = () => {
  if (currentProjectId.value && calculationResult.value) {
    // 构建分析结果数据
    const resultData = {
      // 基本参数
      interfacialTension: calculationResult.value[0]['IFT (mN/m)'],
      volume: calculationResult.value[0]['Volume (uL)'],
      area: calculationResult.value[0]['Area (mm2)'],
      
      // 几何参数
      apexRadius: calculationResult.value[0]['Apex radius (px)'],
      rotation: calculationResult.value[0]['Rotation (degree)'],
      apexCoord: {
        x: calculationResult.value[0]['x-apex (px)'],
        y: calculationResult.value[0]['y-apex (px)']
      },
      
      // 无量纲参数
      bondNumber: calculationResult.value[0]['Bond number'],
      worthingtonNumber: calculationResult.value[0]['Worthington number'],
      
      // 输入参数
      dropDensity: formData.drop_density,
      continuousDensity: formData.continuous_density,
      needleDiameter: formData.needle_diameter_mm
    };
    
    // 发送事件通知项目页面更新数据
    uni.$emit('analysisComplete', {
      projectId: currentProjectId.value,
      type: '水滴张力分析',
      result: resultData
    });
    
    // 显示保存成功提示
    uni.showToast({
      title: '已保存到项目',
      icon: 'success'
    });
    
    // 保存后清除项目ID
    uni.removeStorageSync('currentProjectId');
    
    // 延迟返回到项目页面
    setTimeout(() => {
      uni.navigateBack();
    }, 1500);
  } else {
    if (!currentProjectId.value) {
      uni.showToast({
        title: '未找到项目信息',
        icon: 'none'
      });
    } else if (!calculationResult.value) {
      uni.showToast({
        title: '请先进行计算',
        icon: 'none'
      });
    }
  }
};

// 跳转到区域选择页面
const goToRegionSelector = () => {
  if (!imagePreview.value) {
    uni.showToast({
      title: '请先选择图片',
      icon: 'none'
    });
    return;
  }
  
  // 确保图片路径已经存入缓存
  uni.setStorageSync('analyzedImagePath', imagePreview.value);
  
  // 导航到区域选择页面
  uni.navigateTo({
    url: '/pages/region_selector/region_selector'
  });
};
</script>

<style lang="scss">
// 主题色变量
$primary-color: #4c84ff;
$light-primary: #eef4ff;
$dark-primary: #3a67cc;
$background-color: #f8f9fc;
$card-bg-color: #ffffff;
$text-color: #333333;
$text-secondary: #666666;
$text-muted: #999999;
$border-color: #e8e8f0;
$success-color: #52c41a;
$warning-color: #faad14;
$error-color: #f5222d;

.page-container {
  min-height: 100vh;
  background-color: $background-color;
  padding-bottom: 30px;
  
  .page-header {
    margin-bottom: 25px;
    
    .page-subtitle {
      font-size: 14px;
      color: $text-secondary;
      letter-spacing: 0.5px;
      display: block;
    }
  }
  
  .full-card {
    margin: 0;
    padding: 0;
    
    :deep(.uni-card) {
      margin: 0;
      padding: 0;
      border-radius: 0;
      box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
      
      .uni-card__header {
        padding: 18px 24px;
        border-bottom: 1px solid $border-color;
        background-color: $card-bg-color;
        
        .uni-card__header-title {
          font-size: 20px;
          font-weight: 600;
          color: $text-color;
        }
      }
      
      .uni-card__content {
        padding: 24px;
      }
    }
  }
  
  .section-card {
    background-color: $card-bg-color;
    border-radius: 8px;
    margin-bottom: 20px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    
    :deep(.uni-section) {
      .uni-section__head {
        padding: 12px 16px;
        
        .uni-section__content {
          .uni-section__content-title {
            font-size: 16px;
            font-weight: 600;
            color: $text-color;
          }
        }
      }
    }
    
    .section-content {
      padding: 16px;
      
      .uni-forms-item {
        margin-bottom: 20px;
        
        :deep(.uni-forms-item__inner) {
          .uni-forms-item__label {
            font-size: 14px;
            color: $text-secondary;
            font-weight: 500;
          }
        }
      }
    }
  }
  
  .subsection {
    margin-top: 16px;
    background-color: $light-primary;
    border-radius: 6px;
    
    :deep(.uni-section__head) {
      background-color: rgba($primary-color, 0.1);
    }
  }
  
  .input-group {
    display: flex;
    align-items: center;
    
    .primary-input {
      border-radius: 6px;
      
      :deep(.uni-easyinput__content) {
        background-color: #fff;
        border: 1px solid $border-color;
        height: 40px;
        
        &.is-input-border {
          border-radius: 6px;
        }
        
        .uni-easyinput__placeholder-class {
          color: $text-muted;
        }
      }
    }
    
    .unit {
      margin-left: 12px;
      color: $text-secondary;
      font-size: 14px;
      min-width: 50px;
    }
  }
  
  .custom-number-box {
    :deep(.uni-numbox) {
      height: 36px;
      width: 120px;
      
      .uni-numbox__value {
        background-color: #fff;
        color: $text-color;
      }
      
      .uni-numbox--text {
        background-color: $light-primary;
        color: $primary-color;
        
        &:active {
          background-color: rgba($primary-color, 0.2);
        }
      }
    }
  }
  
  .switch-group {
    display: flex;
    align-items: center;
    gap: 12px;
    
    .custom-switch {
      :deep(.uni-switch-input) {
        background-color: $primary-color !important;
      }
    }
  }
  
  .description {
    font-size: 12px;
    color: $text-muted;
    margin-top: 6px;
    display: block;
  }
  
  .image-section {
    .preview-container {
      width: 100%;
      height: 300px;
      border: 2px dashed lighten($primary-color, 30%);
      border-radius: 8px;
      display: flex;
      justify-content: center;
      align-items: center;
      cursor: pointer;
      background-color: rgba($primary-color, 0.02);
      transition: all 0.3s ease;
      
      &:hover {
        border-color: $primary-color;
        background-color: rgba($primary-color, 0.05);
      }
      
      image {
        max-width: 100%;
        max-height: 100%;
        border-radius: 4px;
        box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
      }
      
      .empty-preview {
        display: flex;
        flex-direction: column;
        align-items: center;
        color: lighten($primary-color, 10%);
        
        text {
          margin-top: 12px;
          font-size: 15px;
        }
      }
    }
  }
  
  .image-actions {
    display: flex;
    gap: 20rpx;
    margin-top: 20rpx;
    
    .action-button {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      height: 70rpx;
      border-radius: 35rpx;
      font-size: 26rpx;
      color: #fff;
      padding: 0 30rpx;
      
      &.select-button {
        background-color: #1890ff;
      }
      
      &.region-button {
        background-color: #52c41a;
        
        &[disabled] {
          background-color: #d9d9d9;
          color: #999;
        }
      }
      
      .button-text {
        margin-left: 10rpx;
      }
    }
  }
  
  .region-status {
    display: flex;
    flex-direction: column;
    gap: 16px;
    
    .region-item {
      display: flex;
      align-items: center;
      gap: 12px;
      
      .region-icon {
        width: 20px;
        height: 20px;
        border-radius: 50%;
        background-color: #ddd;
        
        &.drop-icon {
          background-color: #52c41a;
        }
        
        &.needle-icon {
          background-color: #1890ff;
        }
      }
      
      .region-info {
        display: flex;
        flex-direction: column;
        gap: 4px;
        
        .region-name {
          font-size: 14px;
          font-weight: 600;
          color: $text-color;
        }
        
        .region-detail {
          font-size: 12px;
          color: $text-secondary;
        }
      }
    }
  }
  
  .custom-collapse {
    :deep(.uni-collapse) {
      background-color: $card-bg-color;
      border-radius: 6px;
      overflow: hidden;
      
      .uni-collapse-item {
        border-bottom: 1px solid $border-color;
        
        &:last-child {
          border-bottom: none;
        }
        
        .uni-collapse-item__header {
          padding: 12px 16px;
          background-color: $light-primary;
          
          .uni-collapse-item__header-text {
            color: $text-color;
            font-weight: 500;
          }
          
          .uni-collapse-item__header-arrow-down {
            color: $primary-color;
          }
        }
        
        .uni-collapse-item__wrap {
          background-color: #fff;
        }
      }
    }
  }
  
  .advanced-options {
    padding: 16px;
    border-radius: 5px;
  }
  
  .action-container {
    display: flex;
    justify-content: center;
    gap: 16px;
    margin: 24px 0;
    
    .action-button {
      flex: 1;
      max-width: 180px;
      height: 45px;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 25px;
      
      &:disabled {
        opacity: 0.6;
      }
      
      &.calculate-button {
        background-color: #4c84ff;
      }
      
      &.save-button {
        background-color: #52c41a;
      }
    }
  }
  
  .result-section {
    .result-content {
      padding: 16px;
      
      .json-data {
        .data-group {
          background-color: #f8f9fa;
          border-radius: 8px;
          padding: 16px;
          margin-bottom: 16px;
          border: 1px solid #e9ecef;
          
          &:last-child {
            margin-bottom: 0;
          }
          
          .group-title {
            font-size: 16px;
            font-weight: 600;
            color: $primary-color;
            margin-bottom: 12px;
            padding-bottom: 8px;
            border-bottom: 1px solid #e9ecef;
          }
          
          .data-item {
            display: flex;
            padding: 8px 0;
            
            &:last-child {
              padding-bottom: 0;
            }
            
            .data-label {
              min-width: 120px;
              color: #6c757d;
              font-size: 14px;
            }
            
            .data-value {
              flex: 1;
              font-family: monospace;
              font-size: 14px;
              color: #212529;
            }
            
            .coord-value {
              flex: 1;
              display: flex;
              flex-direction: column;
              gap: 4px;
              font-family: monospace;
              font-size: 14px;
              color: #212529;
            }
          }
        }
      }
    }
  }
}

// 服务器配置样式
.server-config {
  margin-bottom: 20px;
  
  .section-content {
    display: flex;
    flex-direction: column;
    gap: 12px;
  }
  
  .server-input-group {
    display: flex;
    align-items: center;
    
    .server-label {
      width: 100px;
      font-size: 14px;
      color: $text-secondary;
    }
    
    .server-input {
      flex: 1;
    }
  }
  
  .server-save-btn {
    margin-top: 10px;
    background-color: $primary-color;
    color: white;
    border: none;
    border-radius: 4px;
    padding: 8px 16px;
    font-size: 14px;
    align-self: flex-end;
  }
}

// 添加区域选择按钮样式
.image-actions {
  display: flex;
  gap: 20rpx;
  margin-top: 20rpx;
  
  .action-button {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    height: 70rpx;
    border-radius: 35rpx;
    font-size: 26rpx;
    color: #fff;
    padding: 0 30rpx;
    
    &.select-button {
      background-color: #1890ff;
    }
    
    &.region-button {
      background-color: #52c41a;
      
      &[disabled] {
        background-color: #d9d9d9;
        color: #999;
      }
    }
    
    .button-text {
      margin-left: 10rpx;
    }
  }
}
</style> 